<?php

//定时任务相关控制器

namespace hotel\modules\api\controllers;
use hotel\common\models\ActivityLog;
use hotel\common\models\App;
use hotel\common\models\OrdersModel;
use hotel\common\utils\HotelServices;
use hotel\common\utils\MemberServices;
use hotel\common\utils\PayServices;
use Yii;
use yii\base\Controller;
use yii\log\FileTarget;


class TaskController extends Controller
{
	/*
    * 支付成功回调
	*/
	public function actionCallBack()
	{
		$request = \Yii::$app->request;
		$post_data = $request->post();
		$this->recordPay($post_data);
		$payNo = $post_data['payNo'];
		$order   = OrdersModel::find()->where("order_sn = '$payNo'")->asArray()->one();
		$appid = $order['appid'];
		$app_data = App::find()->where("appid = '$appid'")->asArray()->one();
		$data['appId'] = $post_data['appId'];
		$data['payStatus'] = $post_data['payStatus'];
		$data['payNo'] = $post_data['payNo'];
		$data['payTime'] = $post_data['payTime'];
		$data['orderSn'] = $post_data['orderSn'];
		$data['nonceStr'] = $post_data['nonceStr'];
		$data['timeStamp'] = $post_data['timeStamp'];
		$c_sign = PayServices::computeSign($data,false,$app_data['pay_key']);
		$sign = $post_data['sign'];
		if($sign != $c_sign){
			$res =  ['relCode'=>400,'relMsg'=>'签名错误'];
			return json_encode($res, JSON_UNESCAPED_UNICODE);
		}
		if($data['payStatus'] != '00'){
			$res =  ['relCode'=>400,'relMsg'=>'支付未成功'];
			return json_encode($res, JSON_UNESCAPED_UNICODE);
		}

		if($order['order_state']>='2') {
			$res =  ['relCode'=>400,'relMsg'=>'订单已经支付过了'];
			return json_encode($res, JSON_UNESCAPED_UNICODE);
		}

		try{
			//更新订单
			$data = array(
				'pay_time'	=> date("Y-m-d H:i:s"),
				'payment_code'	=> 'weixin',
				'order_state'	=> 2,
			);
			$flag =   OrdersModel::updateAll($data,['order_sn'=>$order['order_sn']]);
			if($flag){
				$session = HotelServices::checkXopSession($appid);
				//西软订单下单
				$dailyrate = [];
				$order_detail = json_decode($order['order_ddetail'],true);
				$days = count($order_detail);
				$fenmu = $days*$order['rmnum'];
				foreach($order_detail as $k=>$v){
					$dailyrate[$k]['rate'] = $order['rate'];
					$dailyrate[$k]['date'] = $v['date'];
					$dailyrate[$k]['pkg'] = $order['pkg'];
					$dailyrate[$k]['rmrate'] = $order['pay_price']/$fenmu;
					$dailyrate[$k]['rtreason'] = '099';
					$dailyrate[$k]['ratecode'] = $order['ratecode'];
				}
				$res = HotelServices::xopsavereservation($session,$appid,$order,$dailyrate);
				if($res['success'] == 1){
					//更新订单xop状态已下单
					$data = array(
						'rsvno' =>$res['results'][0]['rsvno'],
						'accnt' =>$res['results'][0]['accnt'],
						'opx_state'	=> 2,
					);
					OrdersModel::updateAll($data,['order_sn'=>$order['order_sn']]);
					//请求西软修改订单状态
					$order_data   = OrdersModel::find()->where("order_sn = '$payNo'")->asArray()->one();
					$res1 = HotelServices::xopdopaymentaccount($session,$appid,$order_data);
					if($res1['success'] == 1){
						//更新订单xop状态已入账
						$data = array(
							'opx_state'	=> 3,
						);
						OrdersModel::updateAll($data,['order_sn'=>$order['order_sn']]);
						$res =  ['relCode'=>0,'relMsg'=>'订单更新成功'];
						return json_encode($res, JSON_UNESCAPED_UNICODE);
					}else{
						$res =  ['relCode'=>400,'relMsg'=>'xop订单入账失败'];
						return json_encode($res, JSON_UNESCAPED_UNICODE);
					}
				}else{
					$res =  ['relCode'=>400,'relMsg'=>'xop保存订单失败'];
					return json_encode($res, JSON_UNESCAPED_UNICODE);
				}

			}

		}catch(\Exception $e){
			return $e->getMessage();
		}
	}

    /*
    * 支付宝小程序支付成功回调
    */
    public function actionAliCallBack()
    {
        $request = \Yii::$app->request;
        $post_data = $request->post();
        $this->recordPay($post_data);
        $payNo = $post_data['payNo'];
        $order   = OrdersModel::find()->where("order_sn = '$payNo'")->asArray()->one();
        $appid = $order['appid'];
        $app_data = App::find()->where("appid = '$appid'")->asArray()->one();
        $data['appId'] = $post_data['appId'];
        $data['payStatus'] = $post_data['payStatus'];
        $data['payNo'] = $post_data['payNo'];
        $data['payTime'] = $post_data['payTime'];
        $data['orderSn'] = $post_data['orderSn'];
        $data['nonceStr'] = $post_data['nonceStr'];
        $data['attach'] = $post_data['attach'];
        $data['timeStamp'] = $post_data['timeStamp'];
        $c_sign = PayServices::computeSign($data,false,$app_data['ali_pay_key']);
        $sign = $post_data['sign'];
        if($sign != $c_sign){
            $res =  ['relCode'=>400,'relMsg'=>'签名错误'];
            return json_encode($res, JSON_UNESCAPED_UNICODE);
        }
        if($data['payStatus'] != '00'){
            $res =  ['relCode'=>400,'relMsg'=>'支付未成功'];
            return json_encode($res, JSON_UNESCAPED_UNICODE);
        }

        if($order['order_state']>='2') {
            $res =  ['relCode'=>400,'relMsg'=>'订单已经支付过了'];
            return json_encode($res, JSON_UNESCAPED_UNICODE);
        }

        try{
            //更新订单
            $data = array(
                'pay_time'	=> date("Y-m-d H:i:s"),
                'order_state'	=> 2,
            );
            $flag =   OrdersModel::updateAll($data,['order_sn'=>$order['order_sn']]);
//            if($flag){
//                $session = HotelServices::checkXopSession($appid);
//                //西软订单下单
//                $dailyrate = [];
//                $order_detail = json_decode($order['order_ddetail'],true);
//                $days = count($order_detail);
//                $fenmu = $days*$order['rmnum'];
//                foreach($order_detail as $k=>$v){
//                    $dailyrate[$k]['rate'] = $order['rate'];
//                    $dailyrate[$k]['date'] = $v['date'];
//                    $dailyrate[$k]['pkg'] = $order['pkg'];
//                    $dailyrate[$k]['rmrate'] = $order['pay_price']/$fenmu;
//                    $dailyrate[$k]['rtreason'] = '099';
//                    $dailyrate[$k]['ratecode'] = $order['ratecode'];
//                }
//                $res = HotelServices::xopsavereservation($session,$appid,$order,$dailyrate);
//                if($res['success'] == 1){
//                    //更新订单xop状态已下单
//                    $data = array(
//                        'rsvno' =>$res['results'][0]['rsvno'],
//                        'accnt' =>$res['results'][0]['accnt'],
//                        'opx_state'	=> 2,
//                    );
//                    OrdersModel::updateAll($data,['order_sn'=>$order['order_sn']]);
//                    //请求西软修改订单状态
//                    $order_data   = OrdersModel::find()->where("order_sn = '$payNo'")->asArray()->one();
//                    $res1 = HotelServices::xopdopaymentaccount($session,$appid,$order_data);
//                    if($res1['success'] == 1){
//                        //更新订单xop状态已入账
//                        $data = array(
//                            'opx_state'	=> 3,
//                        );
//                        OrdersModel::updateAll($data,['order_sn'=>$order['order_sn']]);
//                        $res =  ['relCode'=>0,'relMsg'=>'订单更新成功'];
//                        return json_encode($res, JSON_UNESCAPED_UNICODE);
//                    }else{
//                        $res =  ['relCode'=>400,'relMsg'=>'xop订单入账失败'];
//                        return json_encode($res, JSON_UNESCAPED_UNICODE);
//                    }
//                }else{
//                    $res =  ['relCode'=>400,'relMsg'=>'xop保存订单失败'];
//                    return json_encode($res, JSON_UNESCAPED_UNICODE);
//                }
//
//            }

        }catch(\Exception $e){
            return $e->getMessage();
        }
    }
//订单推送（恐龙园）
	public function actionPushOrder()
	{
		$tr = Yii::$app->db->beginTransaction();
		$t = date('Y-m-d H:i:s',time() - 1800);
		$data = OrdersModel::find()->where("is_push = 0 and pay_time > '$t' and coupon_from = 1 and order_state != 0 and order_state != 1")->asArray()->all();
		foreach($data as $k=>$v){
			$memberId = $v['kly_member_id'];
			$couponid = $v['couponid'];
			$couponname = $v['couponname'];
			$orderId = $v['id'];
			$paysum = $v['price'];
			$payamount = $v['pay_price'];
			$appid = $v['appid'];
			$res = MemberServices::orderLog($memberId,$couponid,$couponname,$orderId,$paysum,$payamount,$appid);
			if(!$res){
				$tr->rollBack();
				echo '订单推送失败';
			}
			$sql = "update hs_hotel.order set is_push = 1 where id = $orderId ";
			Yii::$app->db->createCommand($sql)->execute();
		}
		$tr->commit();
		echo '订单推送成功';

	}


	/*
    * 活动支付成功回调
    */
	public function actionActivityCallBack()
	{
		$request = \Yii::$app->request;
		$post_data = $request->post();
		$this->recordPay($post_data);
		$payNo = $post_data['payNo'];
		$order = ActivityLog::find()->where("order_sn = '$payNo'")->asArray()->one();
		$data['appId'] = $post_data['appId'];
		$data['payStatus'] = $post_data['payStatus'];
		$data['payNo'] = $post_data['payNo'];
		$data['payTime'] = $post_data['payTime'];
		$data['orderSn'] = $post_data['orderSn'];
		$data['nonceStr'] = $post_data['nonceStr'];
		$data['timeStamp'] = $post_data['timeStamp'];

		if ($data['payStatus'] != '00') {
			$res = ['relCode' => 400, 'relMsg' => '支付未成功'];
			return json_encode($res, JSON_UNESCAPED_UNICODE);
		}

		if ($order['order_state'] >= '2') {
			$res = ['relCode' => 400, 'relMsg' => '订单已经支付过了'];
			return json_encode($res, JSON_UNESCAPED_UNICODE);
		}

		try {
			//更新订单
			$data = array(
				'payment_time' => date("Y-m-d H:i:s"),
				'order_state' => 2,
			);
			$flag = ActivityLog::updateAll($data, ['order_sn' => $order['order_sn']]);
			if ($flag) {
				$res = ['relCode' => 0, 'relMsg' => '订单更新成功'];
				return json_encode($res, JSON_UNESCAPED_UNICODE);
			} else {
				$res = ['relCode' => 400, 'relMsg' => '订单更新失败'];
				return json_encode($res, JSON_UNESCAPED_UNICODE);
			}
		} catch (\Exception $e) {
			return $e->getMessage();
		}
	}
	protected function recordPay($options)
	{
		$log = new FileTarget();
		$log->logFile = \Yii::$app->getRuntimePath() . '/logs/task' . date('Ymd') . '.log';
		$log->messages[] = [
			json_encode($options)
		];
		$log->export();
	}


	public function actionTest()
	{
		$order = OrdersModel::find()->where("order_sn = '680668189600485005'")->asArray()->one();
		$order_detail = json_decode($order['order_ddetail'],true);
		$days = count($order_detail);
		$fenmu = $days*$order['rmnum'];
		$dailyrate = [];
		foreach($order_detail as $k=>$v){
			$dailyrate[$k]['rate'] = $v['rate'];
			$dailyrate[$k]['date'] = $v['date'];
			$dailyrate[$k]['pkg'] = $order['pkg'];
			$dailyrate[$k]['rmrate'] = $order['par_price']/$fenmu;
			$dailyrate[$k]['rtreason'] = '099';
			$dailyrate[$k]['ratecode'] = $order['ratecode'];
		}
		print_r(21);die;
		$appid = $order['appid'];
		$session = HotelServices::checkXopSession($appid);
		//西软订单下单
		$res = HotelServices::xopsavereservation($session, $appid, $order,$dailyrate);
		if ($res['success'] == 1) {
			//更新订单xop状态已下单
			$data = array(
				'rsvno' => $res['results'][0]['rsvno'],
				'accnt' => $res['results'][0]['accnt'],
				'opx_state' => 2,
			);
			OrdersModel::updateAll($data, ['order_sn' => $order['order_sn']]);
			//请求西软修改订单状态
			$order_data = OrdersModel::find()->where("order_sn = 990667511175237115")->asArray()->one();
			$res1 = HotelServices::xopdopaymentaccount($session, $appid, $order_data);
			if ($res1['success'] == 1) {
				//更新订单xop状态已入账
				$data = array(
					'opx_state' => 3,
				);
				OrdersModel::updateAll($data, ['order_sn' => $order['order_sn']]);
				$res = ['relCode' => 0, 'relMsg' => '订单更新成功'];
				return json_encode($res, JSON_UNESCAPED_UNICODE);
			} else {
				$res = ['relCode' => 400, 'relMsg' => 'xop订单入账失败'];
				return json_encode($res, JSON_UNESCAPED_UNICODE);
			}
		}

	}



	}
